// 主入口文件，启动 web 服务
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
// 引入 createProxyMiddleware
const { createProxyMiddleware } = require("http-proxy-middleware");
const axios = require("axios");
const path = require("path");

// 引入路由子模块
const indexRouter = require("./routes/index");
const userRouter = require("./routes/user");

// 创建 express 的 实例
const app = express();

// 注册 req.body 相关的中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 注册 静态资源托管
app.use(express.static(path.resolve(__dirname, "./public")));

// 处理cors - 自动处理
// app.use((req, res, next) => {
//   console.log("11111");
//   // 设置响应头
//   res.set({
//     // 控制允许的请求来源
//     "Access-Control-Allow-Origin": "*",
//     // 控制允许的自定义请求头
//     "Access-Control-Allow-Headers": "content-type",
//     // 控制允许的请求方式
//     "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE",
//   });

//   next();
// });

// 处理cors
app.use(cors());

/**
 * 处理代理，代理到猫眼电影
 * 这块有问题, 目标地址上会多一个 /maoyan
 * http://localhost:3000/maoyan       => https://i.maoyan.com/maoyan
 *
 * http://localhost:3000/maoyan/abc   => https://i.maoyan.com/maoyan/abc
 *
 * http://localhost:3000/maoyan/ajax/moreCinemas    => https://i.maoyan.com/maoyan/ajax/moreCinemas
 *
 *                                 https://i.maoyan.com/ajax/moreCinemas
 */
// app.use(
//   "/maoyan",
//   createProxyMiddleware({
//     // 配置项
//     // 目标服务器地址
//     target: "https://i.maoyan.com",
//     // 虚拟托管站点所需, 一般直接设置为true就好
//     changeOrigin: true,
//   })
// );

/**
 * 处理代理，代理到猫眼电影
 * 这里处理了路径重写
 * http://localhost:3000/maoyan       => https://i.maoyan.com
 *
 * http://localhost:3000/maoyan/abc   => https://i.maoyan.com/abc
 *
 * http://localhost:3000/maoyan/ajax/moreCinemas    => https://i.maoyan.com/ajax/moreCinemas
 *
 * http://localhost:3000/maoyan/ajax/filterCinemas  => https://i.maoyan.com/ajax/filterCinemas
 *
 *                                 https://i.maoyan.com/ajax/moreCinemas
 */
app.use(
  "/maoyan",
  createProxyMiddleware({
    // 配置项
    // 目标服务器地址
    target: "https://i.maoyan.com",
    // 虚拟托管站点所需, 一般直接设置为true就好
    changeOrigin: true,
    // 路径重写
    pathRewrite: {
      "^/maoyan": "",
    },
  })
);

app.use(
  "/mhd",
  createProxyMiddleware({
    target: "https://mhd.zhuishushenqi.com",
    changeOrigin: true,
    // 路径重写
    pathRewrite: {
      "^/mhd": "",
    },
  })
);

// 注册路由中间件
app.use("/", indexRouter);
app.use("/user", userRouter);

// 注册一个路由来访问猫眼
// app.get("/maoyan", (req, res, next) => {
//   // 这里使用的 axios 不是 ajax 操作，直接发的资源请求
//   axios
//     .get(
//       "https://i.maoyan.com/ajax/moreCinemas?movieId=0&day=2022-08-22&offset=0&limit=20&districtId=-1&lineId=-1&hallType=-1&brandId=-1&serviceId=-1&areaId=-1&stationId=-1&item=&updateShowDay=true&reqId=1661132149912&cityId=30&lat=22.62997421532846&lng=113.83205915652873&optimus_uuid=A52DCFB021BA11EDBFF1953403463E7E6E4A2FED2E2A452A8271B88038A2F72A&optimus_risk_level=71&optimus_code=10"
//     )
//     .then((response) => {
//       res.send(response.data);
//     });
// });

// app.get("/maoyan2", (req, res, next) => {
//   axios
//     .get(
//       "https://i.maoyan.com/ajax/filterCinemas?ci=30&optimus_uuid=A52DCFB021BA11EDBFF1953403463E7E6E4A2FED2E2A452A8271B88038A2F72A&optimus_risk_level=71&optimus_code=10"
//     )
//     .then((response) => {
//       res.send(response.data);
//     });
// });

// 定义一个 main 函数
async function main() {
  try {
    // 建立数据库的连接
    await mongoose.connect("mongodb://127.0.0.1:27017/project");
    console.log("数据库连接成功");

    // 监听端口启动服务
    app.listen(3000, () => {
      console.log("服务启动成功");
    });
  } catch (error) {
    console.log("服务启动失败", error);
  }
}

// 调用 main 函数
main();
